package com.briup.corejava.day18;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 第三种创建线程的方法
 * Callable接口
 * call() ， 有返回值，可以得到线程返回的结果
 */
public class Test1 {
    public static void main(String[] args) {
        Callable<?> m1 = new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                // 计算1-50的累加和
                int sum = 0;
                for(int i=1;i<=50;i++){
                    sum += i;
                }
                return sum;
            }
        };
        Callable<?> m2 = new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                // 计算51-100的累加和
                int sum = 0;
                for(int i=51;i<=100;i++){
                    sum += i;
                }
                return sum;
            }
        };
        // 创建ft对象
        FutureTask<?> ft1 = new FutureTask<>(m1);
        FutureTask<?> ft2 = new FutureTask<>(m2);
        // 准备线程
        Thread t1 = new Thread(ft1);
        Thread t2 = new Thread(ft2);
        t1.start();
        t2.start();
        // 将结果合并
        try {
            int r= (Integer)ft1.get()+(Integer)ft2.get();
            System.out.println("1-100的累加和为："+r);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }

    }
}

